<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/entities/Entity.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/entities/Department.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/entities/Indicator.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/entities/Responsibility.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/Service.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/DAO/ResponsibilityDAO.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/exceptions/DataBaseException.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/utils/Str.php';
// удалить, это здесь для тестирования работоспособности!!!
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/ServiceFactory.php';

class ResponsibilityDAOImpl extends ResponsibilityDAO {

	public function create(Entity $responsibility) {
		/*		$sql = 'INSERT INTO `responsibility` (`is_monitoring`,`id_department`,`id_indicator`,`plan_value`';

				$sql .= ') VALUES ("'.$responsibility->isMonitoring().'"';
						$sql .= ','.$responsibility->getDepartment->getIdentity().'"';
						$sql .= ','.$responsibility->getIndicator->getIdentity().'"';

						if($responsibility->getPlanValue() !== null) {
						$sql .= ','.$responsibility->getPlanValue();
						} else $sql .= ',NULL';

						$sql .= ')';

		try {
		$this->query($sql);
		$responsibility->setIdentity($this->identity());
		return $responsibility;
		} catch(DataBaseException $excepton) {
		return null;
		}
		*/

		$is_monitoring = $responsibility->isMonitoring();
		$id_department = $responsibility->getDepartment->getIdentity();
		$id_indicator = $responsibility->getIndicator->getIdentity();
		$plan_value = $responsibility->getPlanValue();

		$stmt = $this->dbh->connection->prepare('INSERT INTO `responsibility` (`is_monitoring`, `id_department`, `id_indicator`, `plan_value`) VALUES (?, ?, ?, ?)');
		$stmt->bindValue(1, $is_monitoring);
		$stmt->bindValue(2, $id_department);
		$stmt->bindValue(3, $id_indicator);
		if($plan_value !== null) {
			$stmt->bindValue(4, $plan_value);
		} else {
			$stmt->bindValue(4, NULL);
		}

		try {
			$this->dbh->query($stmt);
			$responsibility->setIdentity($this->dbh->identity());
			return $responsibility;
		} catch (PDOException $exception) {
			return null;
		}

	}

	public function read($identity) {
		/*		$responsibilities = $this->build('`id`='.(int)$identity);
		 if(count($responsibilities) == 1) {
		return $responsibilities[0];
		} else {
		return null;
		}
		*/

		$id = ((int)$identity);
		$params = array("1"=>$id);

		$responsibilities = $this->build('`id`=?',$params);
		if(count($responsibilities) == 1) {
			return $responsibilities[0];
		} else {
			return null;
		}

	}

	public function update(Entity $responsibility) {
		/*		$sql = 'UPDATE `responsibility` ';
		 $sql .= 'SET `is_monitoring`="'.$responsibility->isMonitoring().'"';
		$sql .= ',`id_department`="'.$responsibility->getDepartment()->getIdentity().'"';
		$sql .= ',`id_indicator`="'.$responsibility->getIndicator()->getIdentity().'"';
			
		if($responsibility->getPlanValue() !== null) {
		$sql .= ',`plan_value`="'.$responsibility->getPlanValue().'"';
		} else $sql .= ',`plan_value`=NULL';

		$sql .= ' WHERE `id`='.$responsibility->getIdentity();

		try {
		$this->query($sql);
		$responsibility->setIdentity($this->identity());
		return $responsibility;
		} catch(DataBaseException $excepton) {
		return null;
		}
		*/

		$is_monitoring = $responsibility->isMonitoring();
		$id_department = $responsibility->getDepartment->getIdentity();
		$id_indicator = $responsibility->getIndicator->getIdentity();
		$plan_value = $responsibility->getPlanValue();
		$id = $responsibility->getIdentity();

		$stmt = $this->dbh->connection->prepare('UPDATE `responsibility` SET `is_monitoring`=?, `id_department`=?, `id_indicator`=?, `plan_value`=? WHERE `id`=?');
		$stmt->bindValue(1, $is_monitoring);
		$stmt->bindValue(2, $id_department);
		$stmt->bindValue(3, $id_indicator);
		if($plan_value !== null) {
			$stmt->bindValue(4, $plan_value);
		} else {
			$stmt->bindValue(4, NULL);
		}
		$stmt->bindValue(5, $id);

		try {
			$this->dbh->query($stmt);
			//$responsibility->setIdentity($this->dbh->identity());
			return $responsibility;
		} catch (PDOException $exception) {
			return null;
		}

	}

	public function delete($responsibility) {
		/*		$sql = 'DELETE FROM `responsibility` ';
		 $sql .= 'WHERE `id`='.((int)$responsibility);
		try {
		$this->query($sql);
		return true;
		} catch(DataBaseException $exception) {
		return false;
		}
		*/

		$id = ((int)$responsibility);

		$stmt = $this->dbh->connection->prepare('DELETE FROM `responsibility` WHERE `id`=?');
		$stmt->bindValue(1, $id);

		try {
			$this->dbh->query($stmt);
			return true;
		} catch (PDOException $exception) {
			return false;
		}

	}

	// создает массив экземпляров класса Responsibility на основе SQL-запроса на выборку с условием $condition
	private function build($condition,$param) {
		/*		$sql = 'SELECT `id`,`is_monitoring`,`id_department`,`id_indicator`';
		 $sql .= 'FROM `responsibility`';
		if($condition !== null) {
		$sql .= ' WHERE '.$condition;
		}
		$this->query($sql);
		$responsibilities = array();
		while($row = $this->row()) {
		$responsibility = new Responsibility();
		$responsibility->setIdentity($row['id']);
		$responsibility->setMonitoring($row['is_monitoring']);

		$department = new Department();
		$department->setIdentity($row['id_department']);
		$responsibility->setDepartment($department);

		$indicator = new Indicator();
		$indicator->setIdentity($row['id_indicator']);
		$responsibility->setIndicator($indicator);

		$responsibilities[] = $responsibility;
		}
		$this->close();
		$serviceDepartment = getService('DepartmentService');// Использовать здесь сервис??????
		foreach($responsibilities as $responsibility) {
		$department = $serviceDepartment->read($responsibility->getDepartment()->getIdentity());
		$responsibility->setDepartment($department);
		}
		$serviceIndicator = getService('IndicatorService');
		foreach($responsibilities as $responsibility) {
		$indicator = $serviceIndicator->read($responsibility->getIndicator()->getIdentity());
		$responsibility->setIndicator($indicator);
		}
		return $responsibilities;
		*/

		$sql = 'SELECT `id`, `is_monitoring`, `id_department`, `id_indicator` FROM `responsibility`';
		if($condition !== null) {
			$sql = ' WHERE '.$condition;
			$stmt = $this->dbh->connection->prepare($sql);
			if($condition !== null) {
				foreach ($param as $i=>$value){
					$stmt->bindValue($i, $value);
				}
			}
			$this->dbh->query($stmt);
		}else{
			$this->dbh->execute($sql);
		}
		$responsibilities = array();
		while($row = $this->dbh->row()) {
			$responsibility = new Responsibility();
			$responsibility->setIdentity($row['id']);
			$responsibility->setMonitoring($row['is_monitoring']);

			$department = new Department();
			$department->setIdentity($row['id_department']);
			$responsibility->setDepartment($department);

			$indicator = new Indicator();
			$indicator->setIdentity($row['id_indicator']);
			$responsibility->setIndicator($indicator);

			$responsibilities[] = $responsibility;
		}
		$this->dbh->close();
		// удалить потом это!!!
// 		$serviceFactoy = new ServiceFactory(); // Создаем фабрику сервисов
// 		$serviceDepartment = $serviceFactoy->getService('DepartmentService');// Получаем нужный сервис
		// это раскомментить, это исходное!!!
		//$serviceDepartment = getService('DepartmentService');// Использовать здесь сервис??????
		foreach($responsibilities as $responsibility) {
			$department = new Department();
			$department->setIdentity($responsibility->getDepartment()->getIdentity());
			$responsibility->setDepartment($department);
		}
// 		// удалить потом это!!!
// 		$serviceIndicator = $serviceFactoy->getService('IndicatorService');// Получаем нужный сервис
		// это раскомментить, это исходное!!!
		//$serviceIndicator = getService('IndicatorService');
		foreach($responsibilities as $responsibility) {
			$indicator = new Indicator();
			$indicator->setIdentity($responsibility->getIndicator()->getIdentity());
			$responsibility->setIndicator($indicator);
		}
		return $responsibilities;

	}

	public function buildWithYear($condition, $year) {
		$responsibilitiesTemp=$this->build($condition);
		$responsibilities = array();
		foreach ($responsibilitiesTemp as $responsibility){
			if($responsibility->getIndicator()->getYear()==$year){
				$responsibilities[]=$responsibility;
			}
		}
		return $responsibilities;
	}

	//получение responsibility
	public function idResponsibility($monitoring,$department,$indicator){
		/*		$sql = 'SELECT `id`,`is_monitoring`,`plan_value`, `id_department`,`id_indicator` FROM `responsibility` WHERE ';
		 $sql .= '`id_department`=';
		$sql .= (int)$department;
		$sql .= ' AND `id_indicator`=';
		$sql .= (int)$indicator;
		$sql .= ';';

		try {
		$this->query($sql);
		$row=$this->row();
		if ($row != NULL){
		$tResponsibility = new Responsibility();
		$tResponsibility ->setIdentity($row['id']);
		$tResponsibility ->setMonitoring($monitoring);
		$tResponsibility ->setPlanValue($row['plan_value']);
		$department = getService('DepartmentService');
		$tResponsibility ->setDepartment($department->read($row['id_department']));
		$indicator = getService('IndicatorService');
		$tResponsibility ->setIndicator($indicator->read($row['id_indicator']));
		return $tResponsibility;
		}else return NULL;
		} catch(DataBaseException $excepton) {
		return null;
		}
		*/

		$department = (int)$department;
		$indicator = (int)$indicator;

		$stmt = $this->dbh->connection->prepare('SELECT `id`,`is_monitoring`, `plan_value`, `id_department`, `id_indicator` FROM `responsibility` WHERE `id_department`=? AND `id_indicator`=?');
		$stmt->bindValue(1, $department);
		$stmt->bindValue(2, $indicator);

		try {
			$this->dbh->query($stmt);
			$row=$this->dbh->row();
			if ($row != NULL){
				$tResponsibility = new Responsibility();
				$tResponsibility ->setIdentity($row['id']);
				$tResponsibility ->setMonitoring($monitoring);
				$tResponsibility ->setPlanValue($row['plan_value']);
				// удалить потом это!!!
// 				$serviceFactoy = new ServiceFactory(); // Создаем фабрику сервисов
// 				$department = $serviceFactoy->getService('DepartmentService');// Получаем нужный сервис
				// это раскомментить, это исходное!!!
				//$department = getService('DepartmentService');
				
				$tResponsibility ->setDepartment($department->read($row['id_department']));
				// удалить потом это!!!
				$indicator = $serviceFactoy->getService('IndicatorService');// Получаем нужный сервис
				// это раскомментить, это исходное!!!
				//$indicator = getService('IndicatorService');
				$tResponsibility ->setIndicator($indicator->read($row['id_indicator']));
				return $tResponsibility;
			}else return NULL;
		} catch (PDOException $exception) {
			return false;
		}

	}

	// добавление записи в таблицу responsibility
	// напрямую, не создавая объект responsibility
	public function putRecord($monitoring,$department,$indicator){
		/*		$sql = 'INSERT INTO `responsibility` (`is_monitoring`,`id_department`,`id_indicator`';

				$sql .= ') VALUES ('.(int)$monitoring;
						$sql .= ','.(int)$department;
						$sql .= ','.(int)$indicator;

						$sql .= ')';

		try {
		$tResponsibility = $this->idResponsibility($monitoring,$department,$indicator);
		if ($tResponsibility != NULL){
		$this->update($tResponsibility);
		return $tResponsibility->getIdentity();
		}else{
		$this->query($sql);
		$idResponsibility = $this->identity();
		return $idResponsibility;
		}
		} catch(DataBaseException $excepton) {
		return null;
		}
		*/

		$is_monitoring = (int)$monitoring;
		$id_department = (int)$department;
		$id_indicator = (int)$indicator;

		$stmt = $this->dbh->connection->prepare('INSERT INTO `responsibility` (`is_monitoring`, `id_department`, `id_indicator`, `plan_value`) VALUES (?, ?, ?, ?)');
		$stmt->bindValue(1, $is_monitoring);
		$stmt->bindValue(2, $id_department);
		$stmt->bindValue(3, $id_indicator);

		try {
			$tResponsibility = $this->idResponsibility($monitoring,$department,$indicator);
			if ($tResponsibility != NULL){
				$this->update($tResponsibility);
				return $tResponsibility->getIdentity();
			}else{
				$this->dbh->query($sql);
				$idResponsibility = $this->dbh->identity();
				return $idResponsibility;
			}
		} catch (PDOException $exception) {
			return null;
		}

	}

	public function putRecordIndicatorValue($quarter,$responsibility){
		/*		$sql = 'INSERT INTO `indicator_value` (`quarter`,`id_responsibility`';

				$sql .= ') VALUES ('.(int)$quarter;
						$sql .= ','.(int)$responsibility;

						$sql .= ')';

		try {
		$this->query($sql);
		$idIndicatorValue = $this->identity();
		return $idIndicatorValue;
		} catch(DataBaseException $excepton) {
		return null;
		}
		*/

		$quarter = (int)$quarter;
		$id_responsibility = (int)$responsibility;

		$stmt = $this->dbh->connection->prepare('INSERT INTO `indicator_value` (`quarter`, `id_responsibility`) VALUES (?, ?)');
		$stmt->bindValue(1, $quarter);
		$stmt->bindValue(2, $id_responsibility);

		try {
			$this->dbh->query($stmt);
			$idIndicatorValue = $this->dbh->identity();
			return $idIndicatorValue;
		} catch (PDOException $exception) {
			return null;
		}

	}

	public function getByDepartment($identity) {
		/*return $this->build('`id_department`='.(int)$identity);*/

		$id = ((int)$identity);
		$params = array("1"=>$id);
		return $this->build('`id_department`=?',$params);

	}

	public function getByDepartmentAndYear($identity, $year) {
		/*return $this->buildWithYear('`id_department`='.(int)$identity,(int)$year);*/

		$id = ((int)$identity);
		$year = ((int)$year);

		$stmt = $this->dbh->connection->prepare('`id_department`=?, ?');
		$stmt->bindParam(1, $id);
		$stmt->bindParam(2, $year);

		return $this->buildWithYear($stmt);

	}

	public function getByYearDepAndIsMonitoring($department, $year) {
		/*return $this->buildWithYear('`id_department`='.(int)$department.' AND `is_monitoring`= 1',(int)$year);*/

		$id = ((int)$department);
		$year = ((int)$year);

		$stmt = $this->dbh->connection->prepare('id_department=? AND is_monitoring=1, ?');
		$stmt->bindParam(1, $id);
		$stmt->bindParam(2, $year);

		return $this->buildWithYear($stmt);

	}

	public function getByIdIndicatorAndYear($identity, $year) {
		/*return $this->buildWithYear('`id_indicator`='.(int)$identity,(int)$year);*/

		$id = ((int)$identity);
		$year = ((int)$year);

		$stmt = $this->dbh->connection->prepare('id_indicator=?, ?');
		$stmt->bindParam(1, $id);
		$stmt->bindParam(2, $year);

		return $this->buildWithYear($stmt);

	}

	//Количество записей связанных с Indicator
	public function countIndicator($id_indicator) {
		/*		$sql = 'SELECT count(id_indicator) FROM `responsibility` WHERE id_indicator=';
		 $sql .= $id_indicator;
		try {
		$this->query($sql);
		$row=$this->row();
		return $row['count(id_indicator)'];
		} catch(DataBaseException $excepton) {
		return null;
		}
		*/

		$stmt = $this->dbh->connection->prepare('SELECT count(id_indicator) FROM responsibility WHERE id_indicator=?');
		$stmt->bindParam(1, $id_indicator);

		try {
			$this->dbh->query($stmt);
			$row=$this->dbh->row();
			return $row['count(id_indicator)'];
		} catch (PDOException $exception) {
			return false;
		}

	}

}

?>